package com.aishua.fire.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import lombok.extern.slf4j.Slf4j;

/**
 * 图片文件工具类
 * @author Administrator
 *
 */
@Slf4j
@Component
public class ImgFileUtil {

	    @Value("${project.imgupload.rootPath}")
	    private String mImagesPath1;
	    
	    @Value("${project.imgreq.rootPath}")
	    private String mImagesPath;
	    
	    @Value("${server.path}")
		private String serverPath;
		
		/*@Value("${proServer.port}")
		private String serverPort;*/
	    
	
	
	/**
	 * 写入文件到本地服务器,返回请求路径
	 * @param file
	 * @return
	 * @throws Exception 
	 */
	public String writeFileInServer(MultipartFile file) throws IOException {
		String mImagesLocalPath="";
		String mImagesPath="";
			mImagesLocalPath=mImagesPath1;
			mImagesPath=this.mImagesPath;
		
		String originalFileName = file.getOriginalFilename();
		String suffix = originalFileName.substring(originalFileName.indexOf("."));
		log.info("上传文件后缀是:{}",suffix);
		
		String fileName = UUID.randomUUID().toString()+suffix;
		String yyyyMM = DateUtils.getNowYYYYMMStr();
		//写入文件
		String rootPath = mImagesLocalPath+"plan/"+yyyyMM+"/";
		writeFile(file, rootPath, fileName);
		//拼接返回请求路径
		//String reqPath =  serverPath+":"+serverPort+mImagesPath+yyyyMM+"/"+fileName;
		String reqPath =  "http://"+serverPath + ":" + "8080" + mImagesPath+"plan/"+yyyyMM+"/"+fileName;
		return reqPath;
	}
	
	
	
	/**
	 * 写入文件到服务器指定路径
	 * @param file
	 * @param rootPath
	 * @param fileName
	 * @throws IOException
	 */
	private void writeFile(MultipartFile file,String rootPath ,String fileName) throws IOException { 
        File targetFile = new File(rootPath);  
        if(!targetFile.exists()){    
            targetFile.mkdirs();    
        }
        //file.transferTo(new File(rootPath+fileName));//下面可以用此替代
        
        FileOutputStream out = new FileOutputStream(rootPath+fileName);
        out.write(file.getBytes());
        out.flush();
        out.close();
    }
	
	
}
